/**
 * 
 */
package de.guidoludwig.af;

import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.table.AbstractTableModel;

import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.CC;
import com.jgoodies.forms.layout.FormLayout;

import de.guidoludwig.jtm.domain.AbstractPersistentObject;

/**
 * @author guido
 * 
 */
public abstract class AbstractHomeView<T extends AbstractPersistentObject> {

	private final AbstractHomeModel<T> model;
	private JComponent preview;

	public AbstractHomeView(AbstractHomeModel<T> model) {
		this.model = model;
	}

	public void setPreview(JComponent preview) {
		this.preview = preview;
	}

	public JComponent buildPanel() {
		String rowSpec = preview == null ? "p, $ug, p" : "p, $ug, p, $rg, f:100dlu:g";
		FormLayout layout = new FormLayout("f:200dlu:g, $ug, 100dlu", rowSpec);
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

		builder.add(buildSearchField(), CC.xy(3, 1));
		builder.add(buildResultList(), CC.xyw(1, 3, 3));
		if (preview != null) {
			builder.add(preview, CC.xyw(1, 5, 3));
		}

		return builder.getPanel();
	}

	protected abstract AbstractTableModel getTableFormat(SelectionInList<T> sil);

	private Component buildResultList() {
		return TableFactory.createTable(model.getSearchResultList(),
				getTableFormat(model.getSearchResultList()));
	}

	private Component buildSearchField() {
		return BasicComponentFactory.createTextField(model.getCriteriaModel(), false);
	}
}
